package com.gistone.commis.api.restController;

import com.gistone.commis.dto.EditorResult;
import com.gistone.commis.dto.FieldError;
import com.gistone.commis.entity.*;
import com.gistone.commis.mapper.CommunityMapper;
import com.gistone.commis.mapper.DepartMapper;
import com.gistone.commis.mapper.CommunityInfoMapper;
import com.gistone.commis.util.DataTablePageUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by wangfan on 2017/5/5.
 */
@RestController("apiCommunityInfoController")
@RequestMapping("api/communityInfo")
public class CommunityInfoController {

    private static final Logger logger = LoggerFactory.getLogger(CommunityInfoController.class);


    @Autowired
    private CommunityInfoMapper communityInfoMapper;

    @Autowired
    private CommunityMapper communityMapper;

    @Autowired
    private DepartMapper departMapper;



    /**
     * 根据id获取社区信息
     * @param id
     * @return
     */

    @RequestMapping(method = RequestMethod.GET, value = "/{id}")
    public CommunityInfo communityInfo(@PathVariable int id) {
        CommunityInfo communityInfo =communityInfoMapper.selectByPrimaryKey(id);
        return communityInfo;
    }







    /**
     * 新建社区信息
     *
     * @param request
     * @param response
     * @return
     */
    @Transactional
    @RequestMapping(method = RequestMethod.POST, value = "/create")
    public Object create(HttpServletRequest request, HttpServletResponse response) {

        HttpSession httpSession = request.getSession();
        User user = (User) httpSession.getAttribute("userInfo");

        CommunityInfo communityInfo = new CommunityInfo();

//        communityInfo.setUserId(user.getUserId());
        EditorResult<CommunityInfo> communityInfoEditorResult = new EditorResult<>();

        List<FieldError> fieldErrorList = new ArrayList<>();

        getCommunityInfo(request, "data[0][", communityInfo,fieldErrorList);
        if (null!=request.getParameter( "communityId")&&!request.getParameter("communityId").isEmpty()) {
            communityInfo.setCommunityId(Integer.valueOf(request.getParameter("communityId")));
            System.out.println(communityInfo.getCommunityId());
            communityInfo.setCommunityName(communityMapper.selectByPrimaryKey(communityInfo.getCommunityId()).getCommunityName());
            System.out.println(communityInfo.getCommunityName());
        }else{
            response.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
        }
        communityInfo.setRegisterTime(new Date());




        if(fieldErrorList.size()>0){
            logger.error("字段格式错误");
            communityInfoEditorResult.setFieldErrors(fieldErrorList);
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            return communityInfoEditorResult;
        }
        if (communityInfoMapper.insertSelective(communityInfo) > 0) {
            List<CommunityInfo> data = new ArrayList<>();
            data.add(communityInfo);
            communityInfoEditorResult.setData(data);

        } else {
            response.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
        }


        return communityInfoEditorResult;
//
    }

    /**
     * 批量修改社区信息， id以,号分割
     *
     * @param communityInfoIdStr
     * @param request
     * @return
     */

    @Transactional
    @RequestMapping(method = RequestMethod.PUT, value = "/edit")
    public Object edit(@RequestParam("id") String communityInfoIdStr, HttpServletRequest request, HttpServletResponse response) {

        HttpSession httpSession = request.getSession();
        User user = (User) httpSession.getAttribute("userInfo");
        String[] arr = communityInfoIdStr.split(",");
        EditorResult<CommunityInfo> communityInfoEditorResult = new EditorResult<>();
        List<CommunityInfo> data =new ArrayList<>();

        for (int i = 0; i < arr.length; i++) {
            int communityInfoId = Integer.valueOf(arr[i]);
            CommunityInfo communityInfo = new CommunityInfo();
            communityInfo.setPkId(communityInfoId);
            List<FieldError> fieldErrorList = new ArrayList<>();
            getCommunityInfo(request, "data[" + communityInfoId + "][", communityInfo,fieldErrorList);
            if(fieldErrorList.size()>0){
                logger.error("字段错误");
                communityInfoEditorResult.setFieldErrors(fieldErrorList);
                response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                return communityInfoEditorResult;
            }
            if (communityInfoMapper.updateByPrimaryKeySelective(communityInfo) > 0) {
                CommunityInfo h = communityInfoMapper.selectByPrimaryKey(communityInfoId);
                data.add(h);


            }else{
                response.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
            }


        }
        communityInfoEditorResult.setData(data);
        return communityInfoEditorResult;


    }


    /**
     * 社区删除
     * 通过社区ID批量删除社区信息， id以,号分割
     *
     * @param communityInfoIdStr
     * @param response
     * @return
     */
    @Transactional
    @RequestMapping(method = RequestMethod.DELETE, value = "/remove")
    public Object remove(@RequestParam("id") String communityInfoIdStr, HttpServletResponse response) {
        String[] arr = communityInfoIdStr.split(",");
        EditorResult<CommunityInfo> communityInfoEditorResult = new EditorResult<>();
        for (int i = 0; i < arr.length; i++) {
            int communityInfoId = Integer.valueOf(arr[i]);
            if (communityInfoMapper.deleteByPrimaryKey(communityInfoId) > 0) {
                System.out.println("删除" + communityInfoId + "成功！");


            } else {
                response.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
            }
        }
        return communityInfoEditorResult;


    }

    /**
     * dataTables 表单数据返回
     *
     * @param request
     * @return
     */

    @Transactional
    @RequestMapping(method = RequestMethod.GET, value = "/pageDatatables")
    public DataTablePageUtil<CommunityInfo> pageDatatables(HttpServletRequest request, CommunityInfo communityInfo) {
/*        HttpSession httpSession = request.getSession();
        User user = (User) httpSession.getAttribute("userInfo");
        logger.info("用户信息：" + user.toString());
        int community_id = user.getCommunity().getCommunityId();
        communityInfo.setCommunityId(community_id);*/






        DataTablePageUtil<CommunityInfo> dataTable = new DataTablePageUtil<>(request);



        PageHelper.startPage(dataTable.getPage_num(), dataTable.getPage_size());
        List<CommunityInfo> list = communityInfoMapper.selectSelective(communityInfo);
        PageInfo<CommunityInfo> pageInfo =new PageInfo<>(list);
        System.out.println(list.size());
        dataTable.setDraw(dataTable.getDraw());
        dataTable.setData(pageInfo.getList());
        dataTable.setRecordsTotal((int)pageInfo.getTotal());
        dataTable.setRecordsFiltered(dataTable.getRecordsTotal());
        //返回数据到页面


        return dataTable;

    }


    private void getCommunityInfo(HttpServletRequest request, String prefix, CommunityInfo communityInfo,  List<FieldError> fieldErrorList ) {

        if (null!=request.getParameter(prefix + "communityId]")&&!request.getParameter(prefix + "communityId]").isEmpty()) {
            communityInfo.setCommunityId(Integer.valueOf(request.getParameter(prefix + "communityId]")));


        }
        communityInfo.setCommunityName(request.getParameter(prefix + "communityName]"));
        try {
            communityInfo.setCommunityArea(Double.valueOf(request.getParameter(prefix + "communityArea]")));
        } catch (NumberFormatException e) {
            logger.error("面积格式不正确，必须为double型");
            FieldError fieldError =new FieldError("communityArea","面积格式不正确，必须为double型");
            fieldErrorList.add(fieldError);
        }
        communityInfo.setCommunityScope(request.getParameter(prefix + "communityScope]"));
        try {
            communityInfo.setCommunityPop(Integer.valueOf(request.getParameter(prefix + "communityPop]")));
        } catch (NumberFormatException e) {
            logger.error("人口格式不正确，必须为整形数字");
            FieldError fieldError =new FieldError("communityPop","人口格式不正确，必须为整形数字");
            fieldErrorList.add(fieldError);
        }
        communityInfo.setCommunityAdd(request.getParameter(prefix + "communityAdd]"));

        communityInfo.setCommunityLeader(request.getParameter(prefix + "communityLeader]"));
        communityInfo.setCommunityXnum(request.getParameter(prefix + "communityXnum]"));
        communityInfo.setCommunityPhone(request.getParameter(prefix + "communityPhone]"));
     /*   try {
            communityInfo.setCommunityPrp(Integer.valueOf(request.getParameter(prefix + "communityPrp]")));
        } catch (NumberFormatException e) {
            logger.error("必须为整形数字");
            FieldError fieldError =new FieldError("communityPrp","必须为整形数字");
            fieldErrorList.add(fieldError);
        }*/

        try {
            communityInfo.setStatus(Integer.valueOf(request.getParameter(prefix + "status]")));
        } catch (NumberFormatException e) {
            logger.error("必须为整形数字");
            FieldError fieldError =new FieldError("status","必须为整形数字");
            fieldErrorList.add(fieldError);
        }

        communityInfo.setDzbsj(request.getParameter(prefix + "dzbsj]"));
        communityInfo.setJwhzr(request.getParameter(prefix + "jwhzr]"));
        communityInfo.setFwzzz(request.getParameter(prefix + "fwzzz]"));
        communityInfo.setFsj(request.getParameter(prefix + "fsj]"));
        communityInfo.setFzr(request.getParameter(prefix + "fzr]"));
        communityInfo.setWy(request.getParameter(prefix + "wy]"));
        communityInfo.setHjs(request.getParameter(prefix + "hjs]"));
        communityInfo.setHjrs(request.getParameter(prefix + "hjrs]"));
        communityInfo.setCzh(request.getParameter(prefix + "czh]"));
        communityInfo.setCzrks(request.getParameter(prefix + "czrks]"));
        communityInfo.setRhfl(request.getParameter(prefix + "rhfl]"));
        communityInfo.setRzhbz(request.getParameter(prefix + "rzhbz]"));
        communityInfo.setHzrbz(request.getParameter(prefix + "hzrbz]"));
        communityInfo.setWlrkh(request.getParameter(prefix + "wlrkh]"));
        communityInfo.setWlrks(request.getParameter(prefix + "wlrks]"));
        communityInfo.setXqdw(request.getParameter(prefix + "xqdw]"));
        communityInfo.setDwrs(request.getParameter(prefix + "dwrs]"));
        communityInfo.setReserveA(request.getParameter(prefix + "reserveA]"));
        communityInfo.setReserveB(request.getParameter(prefix + "reserveB]"));


    }

}
